﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using ServiceKit.JsonRpc;
using System;
using System.Linq;

namespace ServiceKit.WebApi
{
    /// <summary>
    /// https://yq.aliyun.com/ziliao/100255
    /// </summary>
    public class DynamicApiControllerRouteConvention : IApplicationModelConvention
    {
        private RpcServerConfiguration serverConfig { get; }

        public DynamicApiControllerRouteConvention()
        {
            this.serverConfig = RpcContants.RpcConfig ?? throw new ArgumentNullException(nameof(RpcContants.RpcConfig));
        }

        //接口的Apply方法
        public void Apply(ApplicationModel application)
        {
            //遍历所有的 Controller
            foreach (var controller in application.Controllers)
            {
                //// 已经标记了 RouteAttribute 的 Controller
                //var matchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel != null).ToList();

                //if (matchedSelectors.Any())
                //{
                //    foreach (var selectorModel in matchedSelectors)
                //    {
                //        // 在 当前路由上 再 添加一个 路由前缀
                //        selectorModel.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_centralPrefix,
                //         selectorModel.AttributeRouteModel);
                //    }
                //}

                if (controller.ControllerType == typeof(JsonRpcApiGateWayController))
                {
                    // 没有标记 RouteAttribute 的 Controller
                    var unmatchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
                    if (unmatchedSelectors.Any())
                    {
                        foreach (var selectorModel in unmatchedSelectors)
                        {
                            string serviceUrl = serverConfig.Template.Replace("{module}", serverConfig.ModuleName.ToLower()).Replace("{service}", "");
                            if (serviceUrl.EndsWith("/"))
                            {
                                serviceUrl = serviceUrl.Substring(0, serviceUrl.Length - 1);
                            }
                            // 添加一个 路由前缀
                            selectorModel.AttributeRouteModel = new AttributeRouteModel(new RouteAttribute(serviceUrl));
                        }
                    }
                }

                if (controller.ControllerType.IsGenericType && controller.ControllerType != typeof(DynamicApiController<>))
                {
                    // 没有标记 RouteAttribute 的 Controller
                    var unmatchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
                    if (unmatchedSelectors.Any())
                    {
                        foreach (var selectorModel in unmatchedSelectors)
                        {
                            string serviceName = controller.ControllerType.GetGenericArguments()[0].GetConventionalServiceName();
                            string serviceUrl = serverConfig.Template.Replace("{module}", serverConfig.ModuleName.ToLower()).Replace("{service}", serviceName.ToLower());
                            // 添加一个 路由前缀
                            selectorModel.AttributeRouteModel = new AttributeRouteModel(new RouteAttribute(serviceUrl));
                        }
                    }
                }
            }


        }
    }
}
